<template>
  <el-dialog :visible.sync="visible" custom-class="chartgrid_fomrlist_dialog" ref="dialog" :lock-scroll="true"
    title="Add KPI Settings" :close-on-click-modal="false" :close-on-press-escape="false" @open="open" append-to-body
    @close="clearFormData">
    <div v-loading="loading">
      <el-form style="height:80px" :model="dataForm" :inline="true" :rules="dataRule" ref="form" label-width="100px" label-position="top"
        class="userForm-dataForm">
        <!-- <el-form-item label="Name:" prop="formTitle">
          <el-input disabled style="width:252px" v-model="dataForm.formTitle" maxlength="120" show-word-limit></el-input>
        </el-form-item>
        <el-form-item prop="roleIds" label="Role:">
          <el-select disabled v-model="dataForm.roleIds" filterable clearable multiple collapse-tags default-first-option
            :placeholder="$t('custom.dataset.role')" style="width: 90%;">
            <el-option v-for="its in roleList" :key="its.id" :label="its.name" :value="its.roleId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="integration" :label="$t('custom.dataset.integration')">
          <el-select disabled v-model="dataForm.integration" multiple collapse-tags v-loading="integrationLoding"
            :placeholder="$t('custom.dataset.integration')" style="width: 90%;">
            <el-option v-for="its in integrationList" :key="its.subjectCode" :label="its.name"
              :value="its.subjectCode"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Description:" style="margin-left:30px" prop="description">
          <el-input disabled type="textarea" :rows="1" style="width:252px" v-model="dataForm.description"></el-input>
        </el-form-item> -->
        <el-form-item label="" style="float:right;margin-right:0">
          <div style="float:right;padding:25px 0 0">
            <el-button size="small" style="width:80px" @click="clearFormData" :loading="btnLoading">Cancel</el-button>
            <el-button type="primary" style="width:80px" size="small" @click="save" :loading="btnLoading">Save</el-button>
          </div>
        </el-form-item>
      </el-form>
      <FormMaking :dialogData="dataForm" ref="makingForm"></FormMaking>
    </div>
  </el-dialog>
</template>

<script>
import FormMaking from './form-making.vue'
import { unionIntegrationList } from '@/components/storybook/utilties/tools'
export default {
  components: {
    FormMaking
  },
  data () {
    return {
      visible: false,
      loading: false,
      roleList: [],
      dataForm: {
        formTitle: '',
        roleIds: [],
        description: '',
        createTime: '',
        formSchema: '',
        businessType: 'Custom',
        status: 'Published',
        tenantCode: this.$store.state.user.tenantCode,
        integration: []
      },
      integrationList: [],
      integrationLoding: false,
      btnLoading: false
    }
  },
  props:['dataId'],
  watch: {
    visible (val) {
      if (!val) {
        this.clearFormData()
      }
    }
  },
  computed: {
    dataRule () {
      // var validateSymbol = (rule, value, callback) => {
      //   if (!isIncludeSymbol(value)) {
      //     return callback(new Error(this.$t('validate.isIncludeSymbol')))
      //   }
      //   callback()
      // }
      // return {
      //   formTitle: [
      //     { required: true, message: 'Please enter the name', trigger: 'blur', pattern: '[^ \x22]+' },
      //     { validator: validateSymbol, trigger: 'blur' },
      //     { validator: this.nameValidate, trigger: 'blur' }
      //   ],
      //   formSchema: [
      //     { required: true, message: 'Please making the form', trigger: 'blur' }
      //   ],
      //   roleIds: [
      //     { required: true, message: this.$t('validate.required'), trigger: 'blur' }
      //   ],
      //   description: [
      //     { required: true, message: 'Please enter the description', trigger: 'blur', pattern: '[^ \x22]+' }
      //   ]
      // }
    }
  },
  methods: {
    init () {
      this.loading = true
      this.visible = true
      this.getRoleList()
      this.getIntegrationList()
      this.$nextTick(() => {
        if (this.dataForm.formCode) {
          this.getInfo()
        } else {
          this.loading = false
        }
      })
    },
    setRuleList () {
      if (this.roleList.length > 0) {
        this.dataForm.roleIds = this.dataForm.roleIds.filter(e => this.roleList.findIndex(o => o.roleId === e) > -1)
      } else {
        setTimeout(() => {
          this.setRuleList()
        }, 800)
      }
    },
    getInfo () {
      const params = {
        formCode: this.dataForm.formCode
      }
      this.$interface.reports.getFormDataInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = res.data
        this.setRuleList()
        if (this.$refs['makingForm']) {
          this.$refs['makingForm'].queryMakingForm(this.dataForm.formSchema)
        }
        this.loading = false
      })
    },
    getRoleList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.system.getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        }).catch(() => { })
    },
    getIntegrationList () {
      this.integrationLoding = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            tempList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status
            })
          }
          this.integrationList = unionIntegrationList(tempList, 'subjectCode')
          this.integrationLoding = false
        })
        .catch(() => { })
    },
    clearFormData () {
      this.$refs.form.resetFields()
      this.dataForm = {
        formTitle: '',
        roleIds: [],
        description: '',
        createTime: '',
        formSchema: ''
      }
      if (this.$refs.makingForm) {
        this.$refs.makingForm.clearMakingForm()
      }
      this.visible = false
      this.$emit('closeDialog')
    },
    nameValidate (rule, value, callback) {
      var params = {}
      params.formTitle = this.dataForm.formTitle
      if (this.dataForm.formCode) {
        params.formCode = this.dataForm.formCode
      }
      this.$interface.reports.getCheckFromNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return callback(new Error('The name is already exists'))
          }
          callback()
        })
    },
    save () {
      this.btnLoading = true
      this.$refs.form.validate(async pass => {
        if (pass) {
          if(this.dataId){
            await this.$interface.reports.deleteFormDataApi({id:this.dataId})
          }
          const params = {
            ...this.dataForm
          }
          params.formSchema = this.$refs.makingForm.getJson()
          if (params.formSchema.list.length < 1) {
            this.btnLoading = false
            return this.$message.error('Please making the form')
          }
          this.loading = true
          this.$interface.reports.addOrUpdateFormApi(params).then(({ data: res }) => {
            this.btnLoading = false
            if (res.code !== 0) {
              this.loading = false
              return this.$message.error(res.msg)
            } else {
              this.addReportRouter(res.data)
              if (!this.dataForm.formCode) {
                this.visible = false
              }
              this.loading = false
            }
          })
        }else{
          this.btnLoading = false
        }
      })
    },
    open () {
      if (this.$refs.dataForm) {
        this.$refs.dataForm.clearValidate()
      }
    },
    addReportRouter (route) {
      let childrenrouterMenu =
      {
        children: [],
        createDate: null,
        hasChildren: null,
        hideFromMenu: true,
        icon: 'icon-detail',
        id: route.formCode,
        name: 'form-' + route.formTitle,
        param: JSON.stringify({ 'formCode': route.formCode }),
        parentName: null,
        permissions: '0',
        pid: '',
        sort: 0,
        type: 0,
        url: 'mspbots/FormList/FormData/index'
      }
      let menuList = window.SITE_CONFIG['menuList']
      let formList = menuList.find(it => {
        return it.name === 'Form List'
      })
      if (!formList) {
        let arr = []
        menuList.forEach(item => {
          arr = arr.concat(item.children)
        })
        formList = arr.find(it => {
          return it.name === 'Form List'
        })
      }
      formList.children.push(childrenrouterMenu)
    }
  }
}
</script>
<style lang="scss">
.chartgrid_fomrlist_dialog.el-dialog {
  width: 98vw;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);

  .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding: 0 20px 20px !important;

    .userForm-dataForm {
      margin-bottom: 5px;
    }
  }
}
</style>
